import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { Calendar, Toast } from 'antd-mobile';
import '../css/a.css';
import axios from 'axios';

const SignInCalendar = () => {
    const [signedDates, setSignedDates] = useState([]);
    const [isUpdating, setIsUpdating] = useState(false); // 新增状态

    const user = JSON.parse(sessionStorage.getItem('users'));

    const addsign = async (item) => {
        setIsUpdating(true); // 开始更新状态
        try {
            const res = await axios.post('/cxb/addsign', { _id: user._id, signedDates: item });
            if (res.data.code === 200) {
                // 成功后更新本地的 signedDates
                setSignedDates(prevDates => [...prevDates, ...item]);
                Toast.show('签到成功');
            } else {
                Toast.show('签到失败，请重试');
            }
        } catch (error) {
            console.error("Error adding sign-in:", error);
            Toast.show('请求失败，请检查网络');
        } finally {
            setIsUpdating(false); // 请求结束，重置更新状态
        }
    };

    const getsign = async () => {
        if (!user) {
            Toast.show('用户未登录，请先登录');
            return;
        }
        try {
            const res = await axios.get(`/cxb/getsign?_id=${user._id}`);
            if (res.data.code === 200) {
                setSignedDates(res.data.data); // 确保是一个数组
            } else {
                Toast.show('获取签到记录失败');
            }
        } catch (error) {
            console.error("Error fetching sign-in records:", error);
            Toast.show('获取签到记录失败');
        }
    };
    // 
    useEffect(() => {
        getsign();
    }, [])


    const handleDateClick = (date) => {
        if (isUpdating) {
            Toast.show('正在处理，请稍后再试');
            return; // 如果正在更新，则阻止重复点击
        }
        // 
        const currentDate = dayjs(date);
        const monthYear = currentDate.format('YYYY-MM');
        const d = currentDate.date();
        const newSignIn = { monthYear, date: d };
        const isAlreadySigned = signedDates.some(item => item.monthYear === monthYear && item.date === d);
        if (!isAlreadySigned) {
            addsign([newSignIn]); // 如果未签到，则添加签到
        } else {
            Toast.show(`您已经在 ${monthYear}-${d} 日签到过了`); // 使用 Toast 代替 alert
        }
    };

    // useEffect(() => {
    //     getsign();
    //             console.log('51512****',signedDates);
    // }, []);

    return (
        <Calendar
            renderDate={(date) => {
                const currentDate = dayjs(date);
                const monthYear = currentDate.format('YYYY-MM');
                const d = currentDate.date();
                return (
                    <div
                        className={`custom-cell ${signedDates.some(item => item.monthYear == monthYear && item.date == d) ? 'custom-cell-selected' : ''}`}
                        onClick={() => handleDateClick(date)}>
                        {d}
                    </div>
                );
            }}
        />
    );
};

export default SignInCalendar;
